package cn.amebius.simpledocker.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

/**
 * @author 阿伟
 * @date 2023/8/31 20:54
 */
@Component
public class CustomHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 获取路径参数
        UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()).build();
        Integer key = Integer.valueOf(uriComponents.getPathSegments().get(3)); // 假设路径参数在第二层级上
        attributes.put("key", key);
        String containerId = uriComponents.getPathSegments().get(4); // 假设路径参数在第二层级上
        attributes.put("containerId", containerId);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
